using AlibabaCloud.TeaUtil.Models;
using Aliyun.Credentials.Models;
using Vin.Extension.Alibaba.Services;
using Vin.Extension.Framework.Base;
using Vin.Extension.Framework.Sms.Model;
using Vin.Extension.Framework.Sms.Phone.Alibaba.Adapter;
using Vin.Extension.Framework.Sms.Phone.Alibaba.Options;
using Vin.Extension.Framework.Sms.Phone.ServiceInterface;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Attributes;
using Vin.Tool.Core.JsonCategory;

namespace Vin.Extension.Framework.Sms.Phone.Alibaba.Service;

[Service("Alibaba")]
public class AlibabaSendService : VinFrameworkBaseService, ISendSmsService
{
    public object? SenderInfo { get; } = null;
    public string Channel { get; } = "Alibaba";

    [Inject] private readonly DysmsService _dysmsService = null!;

    public async Task<(bool, string)> SendAsync(string businessId, string businessDesc, List<string> receivers,
        string title, string template,
        object? templateData, string content, VinSmsSendOption? option = null)
    {
        if (receivers.Count == 0) return (false, "接收人不能为空");
        if (option is not AlibabaSmsSendOption alibabaOption) return (false, "发送选项不正确");

        var resList = new List<(bool, string)>();
        foreach (var receiver in receivers)
        {
            var (success, message) = await SendAsync(businessId, businessDesc, receiver, title, template,
                templateData, content, alibabaOption);
            resList.Add((success, message));
        }

        return (resList.All(r => r.Item1), string.Join(";", resList.Select(r => r.Item2)));
    }

    public async Task<(bool, string)> SendAsync(string businessId, string businessDesc, string receiver,
        string title, string template,
        object? templateData, string content, AlibabaSmsSendOption option)
    {
        var adapter = VinApp.GetServiceByHttpContext<IAlibabaSmsGetTemplateParam>(option.TemplateCode);
        // if (adapter == null) return (false, "未找到短信模板参数适配器");
        var templateParam = adapter != null
            ? await adapter.GetTemplateParamAsync(template, templateData, content, option)
            : null;
        var res = await _dysmsService.SendSmsAsync(receiver, option.TemplateCode, templateParam, null, null,
            option.SignName);

        return (res.Item1, res.Item2.Body.Message);

        // var sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Dto.SendSmsRequest
        // {
        //     PhoneNumbers = receiver, //"13752302935",
        //     SignName = option.SignName ?? SmsOption.SignName,
        //     TemplateCode = option.TemplateCode,
        //     TemplateParam = await adapter.GetTemplateParamAsync(template, templateData, content, option),
        // };
        // var res = await Client.SendSmsWithOptionsAsync(sendSmsRequest, new RuntimeOptions());
        // var isSuccess = res.Body.Code == "OK";
        // return (isSuccess, AlibabaCloud.TeaUtil.Common.ToJSONString(res));
    }
}